import requests
import json
import time
from datetime import datetime
from apscheduler.schedulers.blocking import BlockingScheduler

# ThingsBoard 配置
THINGSBOARD_URL = "http://192.168.1.42:8181"
ACCESS_TOKEN = "d3uz7le1yh71t2am5lgm"

class SensorReader:
    def read_all(self):
        return {
            "temperature": 25.5,
            "humidity": 60.0,
            "pressure": 1013.25
        }

def send_telemetry(data):
    """发送数据到 ThingsBoard"""
    url = f"{THINGSBOARD_URL}/api/v1/{ACCESS_TOKEN}/telemetry"
    headers = {"Content-Type": "application/json"}
    
    try:
        response = requests.post(
            url,
            headers=headers,
            data=json.dumps(data),
            timeout=10
        )
        response.raise_for_status()
        print(f"[{datetime.now()}] 发送成功！状态码: {response.status_code}")
        print("发送的数据:", data)
        
    except requests.exceptions.RequestException as e:
        print(f"[{datetime.now()}] 发送失败: {str(e)}")

def schedule_job():
    """定时任务配置"""
    scheduler = BlockingScheduler(timezone="Asia/Shanghai")  # 设置时区
    sensor_reader = SensorReader()
    
    def job():
        data = sensor_reader.read_all()
        send_telemetry(data)
    
    # 立即执行一次并每小时重复
    scheduler.add_job(job, 'interval', hours=1, next_run_time=datetime.now())
    scheduler.start()

if __name__ == "__main__":
    try:
        # 手动测试发送
        sensor_reader = SensorReader()
        send_telemetry(sensor_reader.read_all())
        
        # 启动定时任务
        schedule_job()
    except Exception as e:
        print("初始化错误:", str(e))
